<template>
  <div class="p-2">
    <div class="search" v-show="showSearch">
      <el-form
        :model="queryParams"
        ref="queryFormRef"
        :inline="true"
        label-width="68px"
      >
        <el-form-item label="资源名称" prop="name">
          <el-input
            v-model="queryParams.name"
            placeholder="请输入课程名称"
            clearable
            @keyup.enter="handleQuery"
            class="w-200px!"
          />
        </el-form-item>

        <el-form-item label="上传者" prop="uploaderNickName">
          <el-input
            v-model="queryParams.uploaderNickName"
            placeholder="请输入上传者昵称"
            clearable
            @keyup.enter="handleQuery"
            class="w-200px!"
          />
        </el-form-item>

        <el-form-item label="类型" prop="resourceType">
          <el-select
            v-model="queryParams.resourceType"
            clearable
            placeholder="请选择"
          >
            <el-option
              v-for="item in selectArr.typeArr"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="备注信息" prop="remark">
          <el-input
            v-model="queryParams.remark"
            placeholder="请输入备注信息"
            clearable
            @keyup.enter="handleQuery"
            class="w-200px!"
          />
        </el-form-item>

        <el-form-item label="操作时间" prop="age">
          <el-date-picker
            v-model="queryParams.timeRange"
            type="datetimerange"
            range-separator="至"
            start-placeholder="开始时间"
            end-placeholder="结束时间"
            @change="handleDateRangeChange"
          />
        </el-form-item>

        <!-- <el-form-item label="资源范围" prop="age">
          <el-select v-model="resourceRegion" clearable placeholder="Select">
            <el-option
              v-for="item in selectArr.resourceRegionArr"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item> -->

        <el-form-item>
          <el-button type="primary" icon="Search" @click="handleQuery">
            搜索
          </el-button>
          <el-button icon="Refresh" @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>
    </div>

    <el-card shadow="never">
      <!-- 按钮区 -->
      <template #header>
        <el-row :gutter="10" class="mb-1">
          <el-col :span="1.5">
            <el-button
              type="primary"
              plain
              icon="Plus"
              v-hasPermi="['course:resource:add']"
              @click="handleCreate"
            >
              新增
            </el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button
              type="success"
              plain
              icon="Edit"
              :disabled="single"
              v-hasPermi="['course:resource:edit']"
              @click="handleUpdate()"
            >
              修改
            </el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button
              type="danger"
              plain
              icon="Delete"
              :disabled="multiple"
              v-hasPermi="['course:resource:remove']"
              @click="handleDelete()"
            >
              删除
            </el-button>
          </el-col>
          <!-- <el-col :span="1.5">
            <el-button type="info" plain icon="Delete" :disabled="multiple"
              >导入</el-button
            >
          </el-col>
          <el-col :span="1.5">
            <el-button type="info" plain icon="Delete" :disabled="multiple"
              >导出</el-button
            >
          </el-col> -->
          <!-- <el-col :span="1.5">
              <el-button type="warning" plain icon="Download" @click="handleExport" v-hasPermi="['demo:demo:export']">导出</el-button>
            </el-col> -->
          <right-toolbar
            v-model:showSearch="showSearch"
            @queryTable="getResourceList"
          ></right-toolbar>
        </el-row>

        <!-- 列表区 -->
      </template>

      <!-- 列表区 -->
      <el-table
        v-loading="loading"
        :data="resourceList"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="30" align="center" />
        <el-table-column
          label="资源名称"
          align="center"
          prop="name"
          v-if="true"
        />

        <el-table-column label="资源类型" align="center" prop="resourceType">
          <template #default="{ row }: { row: CourseResourceVo }">
            <el-tag type="info">{{ row.resourceTypeMsg }}</el-tag>
          </template>
        </el-table-column>

        <el-table-column label="上传状态" prop="resourceStatus">
          <template #default="{ row }: { row: CourseResourceVo }">
            <el-tag
              :type="
                CourseResourceStatusStyleTypeMap.get(
                  row.resourceStatus ?? -1,
                ) ?? 'info'
              "
            >
              {{ row.resourceStatusMsg }}
            </el-tag>
          </template>
        </el-table-column>

        <el-table-column label="上传者" align="center" prop="createBy" />

        <!-- <el-table-column label="状态" prop="status">
          <template #default="{ row }">
            <el-tag :type="statusType(row.status)">{{ row.status }}</el-tag>
          </template>
        </el-table-column> -->

        <el-table-column label="添加时间" align="center" prop="createTime" />
        <el-table-column label="资源备注信息" align="center" prop="remark" />
        <!-- <el-table-column label="排序" align="center" prop="orderNum" /> -->

        <el-table-column
          label="操作"
          align="center"
          class-name="small-padding fixed-width"
        >
          <template #default="scope">
            <span v-hasPermi="['course:resource:query']">
              <el-tooltip content="详情" placement="top" :enterable="false">
                <el-button
                  link
                  type="primary"
                  icon="FolderOpened"
                  @click="handleDetail(scope.row)"
                ></el-button>
              </el-tooltip>
            </span>
            <span v-hasPermi="['course:resource:edit']" class="ml-10px">
              <el-tooltip content="编辑" placement="top" :enterable="false">
                <el-button
                  link
                  type="primary"
                  icon="Edit"
                  @click="handleUpdate(scope.row)"
                ></el-button>
              </el-tooltip>
            </span>
            <span v-hasPermi="['course:resource:remove']" class="ml-10px">
              <el-tooltip content="删除" placement="top" :enterable="false">
                <el-button
                  link
                  type="primary"
                  icon="Delete"
                  @click="handleDelete(scope.row)"
                ></el-button>
              </el-tooltip>
            </span>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页组件 -->
      <pagination
        v-show="total > 0"
        :total="total"
        v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize"
        @pagination="getResourceList"
      />
    </el-card>

    <el-dialog
      v-model="dialogStatus.isVisible"
      :title="dialogStatus.title"
      width="38%"
      center
      :show-close="false"
      :close-on-click-modal="false"
      @close="handleCloseDialog"
    >
      <el-form
        :model="dialogData"
        ref="dialogFormRef"
        :inline="true"
        label-width="100px"
        class="dialogForm"
        :rules="rules"
      >
        <el-form-item label="资源名称" prop="name">
          <el-input
            :disabled="dialogStatus.isDisabled"
            v-model="dialogData.name"
            placeholder="请输入名称"
            clearable
            @keyup.enter="handleQuery"
            style="width: 220px"
          />
        </el-form-item>

        <el-form-item label="资源类型" prop="status">
          <el-radio-group
            v-model="dialogData.resourceType"
            :disabled="dialogStatus.isDisabled"
          >
            <el-radio label="1">视频</el-radio>
            <el-radio label="2">音频</el-radio>
            <el-radio label="3">文档</el-radio>
          </el-radio-group>
        </el-form-item>

        <!-- <el-form-item label="是否公开" prop="resourceType">
          <el-select
            :disabled="dialogStatus.isDisabled"
            v-model="dialogData.open"
            clearable
            placeholder="Select"
          >
            <el-option
              v-for="item in selectArr.openArr"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item> -->

        <el-row>
          <el-form-item label="资源文件" prop="type">
            <!-- <video
              id="myPlayer"
              style="width: 400px; height: 200px"
              controls
            ></video> -->
            <div v-if="isDetail">
              <!-- 查看详情展示 -->
              <!-- <div id="myPlayer" style="width: 400px; height: 200px"></div> -->
              <div class="flex">
                <div
                  class="mr-20px border-1 border-#2a3347 border-solid relative"
                  style="width: 400px; height: 200px"
                >
                  <img
                    :src="dialogData.coverURL ?? ''"
                    alt="play_button"
                    style="object-fit: contain"
                    class="absolute w-398px h-198px"
                  />
                  <el-tooltip
                    content="开始播放"
                    :enterable="false"
                    placement="top"
                  >
                    <img
                      :src="bigPlayButton"
                      alt="play_button"
                      class="absolute w-64px h-64px left-168px top-68px cursor-pointer"
                      @click="handlePlaySection()"
                    />
                  </el-tooltip>
                </div>
              </div>
              <el-upload class="upload-demo" :before-upload="beforeUpload">
                <template #tip>
                  <div class="el-upload__tip">
                    {{ dialogData.fileName }}
                  </div>
                </template>
              </el-upload>
            </div>

            <div v-else>
              <div v-if="isAdd">
                <!-- 新增资源展示 -->
                <el-upload class="upload-demo" :before-upload="beforeUpload">
                  <el-button type="primary">选择资源文件</el-button>
                  <template #tip>
                    <div class="el-upload__tip">
                      {{ dialogData.fileName }}
                    </div>
                  </template>
                </el-upload>
              </div>
              <!-- 编辑资源展示 -->
              <div v-else>
                <div class="flex">
                  <div
                    class="mr-20px border-1 border-#2a3347 border-solid relative"
                    style="width: 400px; height: 200px"
                  >
                    <img
                    :src="dialogData.coverURL ?? ''"
                      alt="play_button"
                      style="object-fit: contain"
                      class="absolute w-398px h-198px"
                    />
                    <el-tooltip
                      content="开始播放"
                      :enterable="false"
                      placement="top"
                    >
                      <img
                        :src="bigPlayButton"
                        alt="play_button"
                        class="absolute w-64px h-64px left-168px top-68px cursor-pointer"
                        @click="handlePlaySection()"
                      />
                    </el-tooltip>
                  </div>
                </div>
              </div>
            </div>
          </el-form-item>
        </el-row>

        <!-- <el-form-item label="资源文件" prop="type" v-else>
          <el-upload class="upload-demo" :before-upload="beforeUpload">
            <el-button type="primary">选择视频文件</el-button>
            <template #tip>
              <div class="el-upload__tip">
                {{ dialogData.fileName }}
              </div>
            </template>
          </el-upload>
        </el-form-item> -->

        <el-form-item label="备注信息" prop="remark">
          <el-input
            v-model="dialogData.remark"
            :disabled="dialogStatus.isDisabled"
            :autosize="{ minRows: 3, maxRows: 4 }"
            type="textarea"
            placeholder=" "
            style="width: 400px"
          />
        </el-form-item>

        <el-form-item label="关联课程" prop="remark" style="width: 500px">
          <el-table :data="dialogData.sectionList">
            <el-table-column
              label="序号"
              align="center"
              prop="orderNum"
              width="50px"
            >
            </el-table-column>

            <el-table-column label="课程名称" align="center" prop="courseName">
            </el-table-column>

            <el-table-column label="章节" align="center" prop="name">
            </el-table-column>
          </el-table>
        </el-form-item>

        <el-form-item class="dialogFooter">
          <el-button
            type="primary"
            icon="Search"
            @click="addSubmit"
            v-if="dialogStatus.title != '资源详情'"
          >
            提交
          </el-button>
          <el-button icon="Refresh" @click="dialogStatus.isVisible = false">
            关闭
          </el-button>
        </el-form-item>
      </el-form>
    </el-dialog>

    <!-- 上传进度 -->
    <el-dialog
      v-model="dialogStatus.isUploading"
      title="上传中"
      width="14%"
      center
      :show-close="false"
      :close-on-click-modal="false"
      @close="handleCloseDialog"
    >
      <div style="display: flex; text-align: center; justify-content: center">
        <el-progress
          type="circle"
          :color="colors"
          :percentage="currentLoadedPercent"
        />
      </div>
    </el-dialog>

    <!-- 播放器 -->
    <el-dialog
      v-model="dialogStatus.player"
      title="播放章节"
      width="820px"
      @close="handleClosePlayerDialog"
      center
      class="dialog-player"
    >
      <div
        :id="'player-' + dialogStatus.resourceId"
        class="w-800px! h-400px!"
      ></div>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import {
  getAllCourseResource as getAllCourseResourceApi,
  createResource as createResourceApi,
  getResourceDetail as getResourceDetailApi,
  deleteResource as deleteResourceApi,
  updateResource as updateResourceApi,
  getPlayAuth as getPlayAuthApi,
} from "@/service/api/course/resource";
import { ElForm } from "element-plus";
import { to } from "await-to-js";
import {
  CourseResourceVo,
  VodPlayAuth,
  VodUploadAuth,
} from "@/service/api/course/resource/types.ts";
import RightToolbar from "@/components/RightToolbar/index.vue";
import Pagination from "@/components/Pagination/index.vue";
import { BasePageResponse, BaseResponse } from "@/service/api/type.ts";
import {
  CourseResourceStatusMap,
  CourseResourceStatusStyleTypeMap,
} from "@/maps/course/resource/courseResourceStatusMap.ts";
import { CourseResourceTypeMap } from "@/maps/course/resource/courseResourceTypeMap.ts";
import bigPlayButton from "@/assets/images/bigplay.png";
import { convertTimeRange } from "@/utils/request.ts";

const dialogFormRef = ref(ElForm);
const queryFormRef = ref(ElForm);
const tableIds = ref<string[]>([]);
const uploadLoading = ref(false);
// const startTime = ref("");
// const endTime = ref("");
// 进度条颜色
const colors = [
  { color: "#f56c6c", percentage: 20 },
  { color: "#e6a23c", percentage: 40 },
  { color: "#5cb87a", percentage: 60 },
  { color: "#1989fa", percentage: 80 },
  { color: "#6f7ad3", percentage: 100 },
];

// 初始query数据
const initQueryParams = {
  createBy: "",
  name: "",
  uploaderNickName: "",
  resourceType: "",
  remark: "",
  pageSize: 10,
  pageNum: 1,
  orderByColumn: "createTime",
  orderType: "desc",
  params: {
    beginTime: <string | null>null,
    endTime: <string | null>null,
  },
  timeRange: "",
};

declare type CourseResourceVoWithExtra = CourseResourceVo & {
  fileName?: string;
};

// 初始dialog数据
const initDialogData: CourseResourceVoWithExtra = {
  id: "",
  name: "",
  fileName: "",
  resourceType: "1",
  remark: "",
  sectionList: [],
  open: undefined,
};
// 初始dialog状态
const initDialogStatus = {
  isUploading: false,
  isVisible: false,
  title: "",
  isDisabled: false,
  resourceId: "",
  player: false,
};
const data = reactive({
  queryParams: { ...initQueryParams },
  dialogData: { ...initDialogData },
  dialogStatus: { ...initDialogStatus },
  rules: {
    name: [{ required: true, message: "名称不能为空", trigger: "blur" }],
  },
});

const { queryParams, dialogData, dialogStatus, rules } = toRefs(data);

// 选择框数据
const selectArr = reactive({
  // 类型
  typeArr: [
    {
      value: "3",
      label: "文档",
    },
    {
      value: "2",
      label: "音频",
    },
    {
      value: "1",
      label: "视频",
    },
  ],
  // 状态
  // resourceRegionArr: [
  //   {
  //     value: "0",
  //     label: "资源私有",
  //   },
  //   {
  //     value: "1",
  //     label: "公共资源",
  //   },
  //   {
  //     value: "2",
  //     label: "全部资源",
  //   },
  // ],
  // 是否公开
  // openArr: [
  //   {
  //     value: true,
  //     label: "公开",
  //   },
  //   {
  //     value: false,
  //     label: "私有",
  //   },
  // ],
});

const videoFile = ref();
const resKey = ref<VodUploadAuth | undefined>(undefined);
const resourceRegion = ref("2");
const single = ref(true);
const multiple = ref(true);
const resourceUsageCount = ref<number>(0);
const showSearch = ref(true);
const loading = ref(false);
const total = ref(0);
const resourceList = ref<CourseResourceVo[]>([]);
const isDetail = ref(false);
const vid = ref<string>();
const playAuth = ref<string>();
// 是否为新增
const isAdd = ref(true);

/**
 * 获取资源列表（不泄露异常）
 */
const getResourceList = async (): Promise<boolean> => {
  // const userStore = useUserStore();
  console.log(resourceRegion.value);
  // 如果是管理员，则可以获取全部
  // if (resourceRegion.value === "0") {
  //   const [err, res] = await to(getSelfCourseResourceApi(queryParams.value));
  //   if (!err) {
  //     total.value = Number(res.total);
  //     console.log(res);
  //     if (res.rows) {
  //       dataList.value = res.rows;
  //       dataList.value.map((item: any) => {
  //         if (item.resourceStatus === 1) {
  //           item.resourceStatus = "上传成功";
  //         } else if (item.resourceStatus === 2) {
  //           item.resourceStatus = "上传失败";
  //         } else {
  //           item.resourceStatus = "上传中";
  //         }
  //       });
  //       dataList.value.map((item: any) => {
  //         if (item.resourceType === "1") {
  //           item.resourceType = "视频";
  //         } else if (item.resourceType === "2") {
  //           item.resourceType = "音频";
  //         } else {
  //           item.resourceType = "文档";
  //         }
  //       });
  //     }
  //   }
  // } else if (resourceRegion.value === "1") {
  //   const [err, res] = await to(getPublicCourseResourceApi(queryParams.value));
  //   if (!err) {
  //     total.value = Number(res.total);
  //     dataList.value = res.rows;
  //     console.log(res);

  //     if (res.rows) {
  //       dataList.value.map((item: any) => {
  //         if (item.resourceStatus === 1) {
  //           item.resourceStatus = "上传成功";
  //         } else if (item.resourceStatus === 2) {
  //           item.resourceStatus = "上传失败";
  //         } else {
  //           item.resourceStatus = "上传中";
  //         }
  //       });
  //       dataList.value.map((item: any) => {
  //         if (item.resourceType === "1") {
  //           item.resourceType = "视频";
  //         } else if (item.resourceType === "2") {
  //           item.resourceType = "音频";
  //         } else {
  //           item.resourceType = "文档";
  //         }
  //       });
  //     }
  //   }
  // } else if (resourceRegion.value === "2") {
  //   if (userStore.roleKeys.includes("administrator")) {
  const [err, res] = await to<BasePageResponse<CourseResourceVo>, any>(
    getAllCourseResourceApi(queryParams.value),
  );
  if (!err) {
    console.log(res);
    total.value = Number(res?.total ?? 0);
    resourceList.value = res?.rows ?? [];

    resourceList.value.forEach((item: CourseResourceVo) => {
      item.resourceStatusMsg =
        CourseResourceStatusMap.get(item.resourceStatus ?? -1) ?? "未知";
      item.resourceTypeMsg =
        CourseResourceTypeMap.get(item.resourceType ?? "") ?? "未知";
    });

    return true;
  }

  return false;
  //   } else {
  //     ElMessage({
  //       type: "warning",
  //       message: "您不具有该权限",
  //     });
  //     queryParams.value = Object.assign({}, initQueryParams);
  //   }
  // }
};

/**
 * 处理提交查询按钮
 */
const handleQuery = () => {
  // startTime.value = timeFormate(time.value[0]);
  // endTime.value = timeFormate(time.value[1]);
  // console.log(startTime.value, endTime.value);
  getResourceList();
};

/**
 * 将选择的开始结束日期转换为后端需要的形式
 * @param value
 */
const handleDateRangeChange = (value: [Date | null, Date | null]) => {
  console.log(value);
  queryParams.value.params = convertTimeRange(value);
};

/**
 * 处理重置按钮
 */
const resetQuery = () => {
  queryFormRef.value.resetFields();
  queryParams.value.timeRange = "";
  queryParams.value.params = {
    beginTime: <string | null>null,
    endTime: <string | null>null,
  };
  getResourceList();
};

/**
 * 处理新增按钮
 */
const handleCreate = async () => {
  dialogStatus.value.title = "新增资源";
  dialogStatus.value.isVisible = true;
  isAdd.value = true;
};

const currentLoadedPercent = ref(0);

/**
 * 上传之前获得文件
 * @param file
 */
const beforeUpload = async (file: any) => {
  // 获取资源
  videoFile.value = file;
  // 获取文件名
  dialogData.value.fileName = file.name;
  // 阻断element组件自定义的行为
  return false;
};

/**
 * 初始化上传
 */
const initupload = () => {
  return new AliyunUpload.Vod({
    //userID，必填，您可以使用阿里云账号访问账号中心（https://account.console.aliyun.com/），即可查看账号ID
    userId: "1424582593277949",
    //上传到视频点播的地域，默认值为'cn-shanghai'，
    //eu-central-1，ap-southeast-1
    region: "",
    //分片大小默认1 MB，不能小于100 KB（100*1024）
    partSize: 1048576,
    //并行上传分片个数，默认5
    parallel: 5,
    //网络原因失败时，重新上传次数，默认为3
    retryCount: 3,
    //网络原因失败时，重新上传间隔时间，默认为2秒
    retryDuration: 2,
    //开始上传
    // onUploadstarted: (uploadInfo) => {},
    // //文件上传成功
    // onUploadSucceed: async function (uploadInfo: any) {
    //   console.log(uploadInfo);
    //   await getList();
    //   ElMessage({
    //     message: "新增成功",
    //     type: "success",
    //   });
    //   dialogData.value = Object.assign({}, initDialogData);
    //   dialogStatus.value = Object.assign({}, initDialogStatus);
    //   isDetail.value = false;
    //   loading.value = false;
    //   uploadLoading.value = false;
    // },
    // 文件上传失败
    onUploadFailed: function (uploadInfo: any, code: any, message: any) {
      console.log(uploadInfo, code, message);
    },
    //文件上传进度，单位：字节
    // onUploadProgress: function (uploadInfo, totalSize, loadedPercent) {},
    // //上传凭证或STS token超时
    // onUploadTokenExpired: function (uploadInfo) {},
    // //全部文件上传结束
    // onUploadEnd: function (uploadInfo) {},
  });
};

const send = async () => {
  uploadLoading.value = true;
  console.log(1);

  return new Promise<void>((resolve, reject) => {
    // 获取上传实例
    const uploader = initupload();
    // 添加上传文件
    uploader.addFile(videoFile.value);
    // 获取凭证并设置
    uploader.options.onUploadstarted = async (uploaderInfo: any) => {
      const [err, res] = await to<BaseResponse<VodUploadAuth>, any>(
        createResourceApi(dialogData.value),
      );
      if (!err) {
        console.log(res);
        resKey.value = res?.data ?? undefined;
        uploader.setUploadAuthAndAddress(
          uploaderInfo,
          resKey?.value?.uploadAuth ?? "",
          resKey?.value?.uploadAddress ?? "",
          resKey?.value?.vid ?? "",
        );
      } else {
        console.log(err);
      }
    };
    // 开始上传
    uploader.startUpload();
    // 上传成功
    uploader.options.onUploadSucceed = async (uploadInfo: any) => {
      // resolve();
      console.log(uploadInfo);
    };

    // 上传进度
    uploader.options.onUploadProgress = async (
      uploadInfo: any,
      totalSize: any,
      loadedPercent: any,
    ) => {
      currentLoadedPercent.value = Math.floor(loadedPercent * 100);
      console.log(uploadInfo, totalSize, loadedPercent);
      if (currentLoadedPercent.value === 100) {
        setTimeout(async () => {
          await getResourceList();
          ElMessage({
            message: "新增成功",
            type: "success",
          });
          currentLoadedPercent.value = 0;
          dialogData.value = Object.assign({}, initDialogData);
          dialogStatus.value = Object.assign({}, initDialogStatus);
          isDetail.value = false;
          loading.value = false;
          uploadLoading.value = false;
          dialogStatus.value.isUploading = false;
          resolve();
        }, 1000);
      }
    };
    // 上传失败
    uploader.options.onUploadFailed = (
      uploadInfo: any,
      code: any,
      message: any,
    ) => {
      console.log(uploadInfo, code, message);
      reject(message);
    };
  });
};

const currentPlayer = ref();

//
/**
 * 处理查看详情按钮
 * @param row
 */
const handleDetail = async (row?: any) => {
  const [err, res] = await to<BaseResponse<CourseResourceVo>, any>(
    getResourceDetailApi(row.id),
  );
  if (!err) {
    console.log(res?.data);
    // 获取vid
    vid.value = res?.data?.vid ?? "";
    isDetail.value = true;
    dialogStatus.value.isVisible = true;
    dialogData.value = res?.data ?? initDialogData;
    dialogStatus.value.title = "资源详情";
    dialogStatus.value.isDisabled = true;
    currentSectionId.value = res?.data?.id ?? "";
  }
};

const currentSectionId = ref();
/**
 * 处理编辑按钮
 * @param row
 */
const handleUpdate = async (row?: any) => {
  dialogStatus.value.title = "编辑资源";
  isAdd.value = false;

  const id = row.id || tableIds.value[0];

  const [err, res] = await to<BaseResponse<CourseResourceVo>, any>(
    getResourceDetailApi(id),
  );
  if (!err) {
    console.log(res);
    vid.value = res?.data?.vid ?? "";
    currentSectionId.value = res?.data?.id;
    dialogData.value = res?.data ?? initDialogData;
    dialogStatus.value.isVisible = true;
  }
};

const dialogPlayer = ref();

/**
 * 播放章节视频
 * @param sectionId
 * @param vid
 */
const handlePlaySection = async () => {
  if (vid.value) {
    dialogStatus.value.resourceId = currentSectionId.value;
    const [err, res] = await to<BaseResponse<VodPlayAuth>, any>(
      getPlayAuthApi(vid.value ?? ""),
    );
    if (!err) {
      const playAuth: string = res?.data?.playAuth ?? "";
      dialogStatus.value.player = true;
      await nextTick(() => {
        dialogPlayer.value = new Aliplayer({
          id: "player-" + dialogStatus.value.resourceId,
          width: "100%",
          vid: vid.value, //必选参数。音视频ID。示例：1e067a2831b641db90d570b6480f****。
          playauth: playAuth, //必选参数。音视频播放凭证。
          autoplay: true,
          preload: true,
        });
      });
    } else {
      ElMessage({
        type: "info",
        message: "未绑定视频",
      });
    }
  }
};

/**
 * 关闭播放对话框
 */
const handleClosePlayerDialog = () => {
  if (dialogPlayer.value) {
    dialogPlayer.value.dispose();
  }
};

/**
 * 删除按钮
 * @param row
 */
const handleDelete = async (row?: CourseResourceVo) => {
  console.log(tableIds.value);
  // 单个删除
  if (row) {
    const count = row?.sectionList?.length ?? 0;
    // 弹出删除确认框
    const [err, confirm] = await to<string, string>(
      ElMessageBox.confirm(
        count > 0
          ? `该资源已经被${count}章节使用，`
          : "" + "是否确定删除选中的资源？",
        "警告",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        },
      ),
    );
    if (err === "cancel") {
      ElMessage({
        type: "info",
        message: "取消删除",
      });
    } else if (confirm === "confirm") {
      const [err] = await to<BaseResponse<any>, any>(
        deleteResourceApi(row?.id ?? ""),
      );
      if (!err) {
        ElMessage({
          message: "删除成功",
          type: "success",
        });
        await getResourceList();
      }
    }
  }
  // 批量
  else {
    // 弹出删除确认框
    const [err, confirm] = await to<string, string>(
      ElMessageBox.confirm(
        resourceUsageCount.value > 0
          ? "选中的资源已经在使用中，"
          : "" + "是否确定删除选中的资源？",
        "警告",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        },
      ),
    );
    if (err === "cancel") {
      ElMessage({
        type: "info",
        message: "取消删除",
      });
    } else if (confirm === "confirm") {
      const [err] = await to<BaseResponse<any>, any>(
        deleteResourceApi(tableIds.value),
      );
      if (!err) {
        ElMessage({
          message: "删除成功",
          type: "success",
        });
        await getResourceList();
      }
    }
  }
};

/**
 * 提交按钮
 */
const addSubmit = () => {
  dialogFormRef.value.validate(async (valid: boolean) => {
    // 验证通过
    if (valid) {
      // 有id为编辑
      if (dialogData.value.id) {
        loading.value = true;
        const [err, res] = await to<BaseResponse<any>, any>(
          updateResourceApi(dialogData.value),
        );
        console.log(res, dialogData.value);
        if (!err) {
          setTimeout(async () => {
            await getResourceList();
            ElMessage({
              message: "编辑成功",
              type: "success",
            });
            dialogData.value = Object.assign({}, initDialogData);
            dialogStatus.value = Object.assign({}, initDialogStatus);
            isDetail.value = false;
            loading.value = false;
          }, 1500);
        }
      }
      // 无id为新建
      else {
        console.log(1);
        dialogStatus.value.isUploading = true;
        const [err] = await to(send());
        if (!err) {
          // 新建成功
        } else {
          console.log(err);
        }
      }
      loading.value = false;
    }
  });
};

/**
 * 处理关闭dialog
 */
const handleCloseDialog = () => {
  // 初始化
  dialogData.value = Object.assign({}, initDialogData);
  isDetail.value = false;
  dialogStatus.value.isDisabled = false;
  dialogStatus.value.isVisible = false;
  if (currentPlayer.value) {
    // 如果生成过播放器
    currentPlayer.value.dispose();
    currentPlayer.value = "";
  }
  vid.value = "";
  dialogStatus.value = Object.assign({}, initDialogStatus);
  getResourceList();
};

/**
 * 列表选中变化时触发
 * @param selection
 */
const handleSelectionChange = (selection: CourseResourceVo[]) => {
  tableIds.value = selection
    .map((item: CourseResourceVo) => item.id ?? "")
    .filter((id: string) => id === "");
  resourceUsageCount.value = selection.filter(
    (item: CourseResourceVo) => (item.length ?? 0) > 0,
  ).length;
  console.log(tableIds.value);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
};

onMounted(() => {
  getResourceList();
});
</script>

<style scoped>
.dialogFooter {
  margin: 30px 0 0 65%;
}
</style>
